// request.js
import axios from 'axios'
import { Toast } from 'vant'
import router from '@/router'
import store from '@/store'
const request = axios.create({
  baseURL: process.env.VUE_APP_API_URL,
  timeout: 100000 // 请求超时时间
})
// 不需要loading加载
const requestloading = axios.create({
  baseURL: process.env.VUE_APP_API_URL,
  timeout: 100000 // 请求超时时间
})
function startLoading () {
  // 开始加载
  Toast.loading({
    message: '加载中...',
    forbidClick: true
  })
}
function endLoading () {
  // 结束加载
  Toast.clear()
}

// 添加request拦截器 加载loading
requestloading.interceptors.request.use(config => {
  startLoading()
  // 发送请求的相关逻辑
  const token = store.state.token
  // 判断token存在再做配置
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, error => {
  Promise.reject(error)
})
// 添加respone拦截器 加载loading
requestloading.interceptors.response.use(
  response => {
    endLoading()
    return Promise.resolve(response.data)
  },
  error => {
    startLoading()
    const refreshToken = store.state.refreshToken
    const reRquest = error.config
    if (error.response) {
      switch (error.response.status) {
        case 401:
          if (refreshToken) {
            const params = {
              refresh: refreshToken
            }
            request.post('token/refresh/', params)
              .then(res => {
                store.commit('setToken', res.data.access)
                reRquest.headers.Authorization = `Bearer ${res.data.access}`
                return request(reRquest)
              })
              .catch(err => {
                console.error(err)
              })
          } else {
            const toast = Toast.loading({
              duration: 0, // 持续展示 toast
              forbidClick: true,
              message: '用户需要登录 1 秒'
            })
            let second = 1
            const timer = setInterval(() => {
              second--
              if (second) {
                toast.message = `用户需要登录 ${second} 秒`
              } else {
                clearInterval(timer)
                // 手动清除 Toast
                Toast.clear()
                router.push('/login')
              }
            }, 1000)
          }
          break
        case 403:
          console.log(403)
          break
        case 404:
          Toast({
            message: '网络请求不存在',
            duration: 1500,
            forbidClick: true
          })
          console.log(404)
          break
        case 500:
          console.log(500)
          Toast.fail('错误，请联系管理员')
          break
      }
    }
    return Promise.reject(error.response)
  }
)
// export default request

// 添加request拦截器 不加载loading
request.interceptors.request.use(config => {
  // 发送请求的相关逻辑
  const token = store.state.token
  // 判断token存在再做配置
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, error => {
  Promise.reject(error)
})
// 添加respone拦截器 不加载loading
request.interceptors.response.use(
  response => {
    return Promise.resolve(response.data)
  },
  async error => {
    startLoading()
    const refreshToken = store.state.refreshToken
    const reRquest = error.config
    if (error.response) {
      switch (error.response.status) {
        case 401:
          if (refreshToken) {
            const params = {
              refresh: refreshToken
            }
            request.post('token/refresh/', params)
              .then(res => {
                store.commit('setToken', res.data.access)
                reRquest.headers.Authorization = `Bearer ${res.data.access}`
                return request(reRquest)
              })
              .catch(err => {
                console.error(err)
              })
          } else {
            const toast = Toast.loading({
              duration: 0, // 持续展示 toast
              forbidClick: true,
              message: '用户需要登录 1 秒'
            })
            let second = 1
            const timer = setInterval(() => {
              second--
              if (second) {
                toast.message = `用户需要登录 ${second} 秒`
              } else {
                clearInterval(timer)
                // 手动清除 Toast
                Toast.clear()
                router.push('/login')
              }
            }, 1000)
          }
          break
        case 403:
          console.log(403)
          break
        case 404:
          Toast({
            message: '网络请求不存在',
            duration: 1500,
            forbidClick: true
          })
          console.log(404)
          break
        case 500:
          console.log(500)
          Toast.fail('错误，请联系管理员')
          break
      }
    }
    return Promise.reject(error.response)
  }
)

export const req = request
export const reqloading = requestloading
